//
//  HWOAuthViewController.swift
//  WeiBo
//
//  Created by macbook on 16/6/28.
//  Copyright © 2016年 buWangChuXing. All rights reserved.
//

import UIKit
import SVProgressHUD

class HWOAuthViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
        setupNavItems()
        
//        替换view
        view = webView
    }
    
    
    //设置nav上的两个item 
    private func setupNavItems(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(HWOAuthViewController.cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(HWOAuthViewController.autoFillClick))
    
    }
    
    //取消按钮的实现
    func cancelClick(){
    
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    //js注入按钮的实现
    func autoFillClick(){
    
        let jsSting = "document.getElementById('userId').value='958043696@qq.com',document.getElementById('passwd').value='buzhiduicuo'"
        
        //js注入
        webView.stringByEvaluatingJavaScriptFromString(jsSting)
        

    }
    
    //懒加载webView 拼接两个参数 获取token 通过UIWebView的代理方法
    private lazy var webView:UIWebView = {
    
        let webView = UIWebView()
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")
        
        //创建请求的url 
        let request = NSURLRequest(URL:url!)
        

        //webView加载请求
        webView.loadRequest(request)
        
        webView.delegate = self
        return webView
    }()
    
}

extension HWOAuthViewController:UIWebViewDelegate{
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        
      SVProgressHUD.show()
    }
    
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //把Url转换成字符串
        let url = request.URL?.absoluteString
        
        //判断URl是否有值
//        url?.hasPrefix(<#T##prefix: String##String#>) 授权回调页
        if let u = url where u.hasPrefix(REDIRECT_URI){
        
            let qusest = request.URL?.query
            
            //在判断可选值
            if let q = qusest {
                
                //截取字符串
                let code = q.substringFromIndex("code=".endIndex)
                
                print(code)
            }
            
        }
        return true
        
    }
}



